import pymysql
import json
from flask import Flask,request;
from flask_cors import CORS;

app = Flask(__name__)
CORS(app, supports_credentials=True)

@app.route('/DataCatch',methods = ['GET','POST'])
def DataCatch():
    data = request.args.get("table")
    print(data)
    return GetData(data)#返回一个值。

@app.route('/DataAdd',methods = ['GET','POST'])
def DataAdd():
    table = request.args.get("table")
    data = request.args.get("data")
    print(table, json.loads(data))
    res = AddData(table, json.loads(data))
    if res:
        return 'success'
    else:
        return 'fail'

def GetData(table):
    db = pymysql.connect(
        host='localhost',
        user='root',
        # port=3309,
        password='abc123456',
        database='workshop',
        charset='utf8'
    )
    cursor = db.cursor()
    cursor.execute("SELECT * FROM workshop." + table + ";")
    result = cursor.fetchall()
    des = cursor.description
    resList = []
    desList = []
    data = []
    for index in result:
        resList.append(list(index))
    for desindex in des:
        desList.append(list(desindex)[0])
    for indexi,valuei in enumerate(resList):
        _data = dict()
        for indexj,valuej in enumerate(valuei):
            _data[desList[indexj]] = valuei[indexj]
        data.append(_data)
    return {'code': 0, 'data': data}

def AddData(table, data):
    db = pymysql.connect(
        host='localhost',
        user='root',
        # port=3309,
        password='abc123456',
        database='workshop',
        charset='utf8'
    )
    cursor = db.cursor()

    valuelist = []
    for item in data.values():
        valuelist.append("\'"+ str(item) +"\'")
    print(valuelist)

    sql = 'INSERT INTO workshop.' + table + ' (' + ",".join(data.keys()) + ') VALUES (' + ",".join(valuelist) + ');'
    # INSERT INTO `workshop`.`csworkshop` (`ProTime`, `ProNum`, `ProCondition`, `Message`, `ID`) VALUES ('1664245787032', '2', '合格', '111', '5');
    print(sql)
    cursor.execute(sql)
    db.commit()
    return 1

if __name__ == '__main__':
    app.run()